package com.starry.home.ui.mine

import android.annotation.SuppressLint
import android.content.Context
import android.content.Intent
import android.view.View
import android.widget.Toast
import com.github.gzuliyujiang.wheelpicker.AddressPicker
import com.github.gzuliyujiang.wheelpicker.BirthdayPicker
import com.github.gzuliyujiang.wheelpicker.SexPicker
import com.github.gzuliyujiang.wheelpicker.annotation.AddressMode
import com.github.gzuliyujiang.wheelpicker.contract.OnAddressPickedListener
import com.github.gzuliyujiang.wheelpicker.contract.OnDatePickedListener
import com.github.gzuliyujiang.wheelpicker.contract.OnOptionPickedListener
import com.github.gzuliyujiang.wheelpicker.entity.CityEntity
import com.github.gzuliyujiang.wheelpicker.entity.CountyEntity
import com.github.gzuliyujiang.wheelpicker.entity.ProvinceEntity
import com.github.gzuliyujiang.wheelpicker.entity.SexEntity
import com.starry.core.base.BaseActivity
import com.starry.core.constant.GlobalConfig
import com.starry.core.ext.singleClick
import com.starry.core.ext.toast
import com.starry.core.utils.SpUtil
import com.starry.core.utils.ZKStatusBarUtil
import com.starry.home.R
import com.starry.home.databinding.ActivityUserInfoBinding
import com.starry.home.logic.model.login.UserInfoBean
import com.starry.home.ui.main.MainActivity
import com.starry.home.viewmodel.main.UserInfoViewModel


/**
 * Package:com.starry.dotpen_patients.ui.main
 * Author:starr
 * Time:2024/1/30 19:36
 * Description: 完善个人信息页面
 */
class UserInfoActivity : BaseActivity<ActivityUserInfoBinding, UserInfoViewModel>(),
    OnDatePickedListener, OnOptionPickedListener, OnAddressPickedListener {


    private lateinit var mSexOption: Array<String>

    private lateinit var userInfoBean: UserInfoBean

    private var userId: Int? = null

    companion object {
        fun startAction(context: Context) {
            val intent = Intent(context, UserInfoActivity::class.java)
            context.startActivity(intent)
        }
    }

    override fun initData() {
        mDataBinding.titleTopBar.baseIvBack.singleClick { finish() }
        mDataBinding.titleTopBar.baseIvBack.visibility = View.VISIBLE
        mDataBinding.titleTopBar.baseTvTitle.text = "完善个人信息"
        userId = SpUtil.getIntValue(GlobalConfig.userId)


        mViewModel.getUserInfo(userId!!)

        //获取用户信息
        mViewModel.userInfo.observe(this) {
            if (it.isSuccess) {
                it.getOrNull()?.let { it1 ->
                    userInfoBean = it1.emrHzInfo
                    mDataBinding.etName.setText(userInfoBean.emrHzName)
                    mDataBinding.etAge.setText(userInfoBean.emrHzAge.toString())
                    mDataBinding.etSex.setText(userInfoBean.emrHzSex)
                    mDataBinding.etPlace.setText(userInfoBean.emrHzPlace)
                    mDataBinding.etJob.setText(userInfoBean.emrHzJob)
                    mDataBinding.etBirth.setText(userInfoBean.emrHzBirth)
                    mDataBinding.etMarry.setText(userInfoBean.emrHzMarry)
                }
            } else {
                Toast.makeText(
                    getContext(),
                    "用户信息异常，请重新登录 ${it.exceptionOrNull()?.message}",
                    Toast.LENGTH_SHORT
                ).show()
            }
        }

        mViewModel.responseBean.observe(this) {
            if (it.isSuccess) {
                it.getOrNull()?.let {
                    SpUtil.setStringValue(GlobalConfig.userName, userInfoBean.emrHzName)
                    SpUtil.setStringValue(GlobalConfig.userImg, userInfoBean.emrHzImg)
                    Toast.makeText(getContext(), "用户信息提交成功", Toast.LENGTH_SHORT).show()
                    MainActivity.startAction(getContext())
                    finish()
                }
            } else {
                Toast.makeText(
                    getContext(),
                    "用户信息更新异常 ${it.exceptionOrNull()?.message}",
                    Toast.LENGTH_SHORT
                ).show()
            }
        }
    }

    override fun initView() {
        ZKStatusBarUtil.setTransparentForWindow(this)
        ZKStatusBarUtil.setDarkMode(this)
        mDataBinding.click = UserInfoClick()
    }


    override fun getLayoutId() = R.layout.activity_user_info

    inner class UserInfoClick {
        /**
         * 设置出生日期
         */
        public fun birth(view: View) {
            val picker = BirthdayPicker(this@UserInfoActivity)
            picker.setDefaultValue(1991, 11, 11)
            picker.setOnDatePickedListener(this@UserInfoActivity)
            picker.wheelLayout.setResetWhenLinkage(false)
            picker.show()
        }

        /**
         * 选择性别
         */
        public fun sex(view: View) {

            val picker = SexPicker(this@UserInfoActivity)
            picker.setBodyWidth(140)
            picker.setIncludeSecrecy(false)
            picker.setDefaultValue("女")
            picker.setOnOptionPickedListener(this@UserInfoActivity)
            picker.wheelLayout
                .setOnOptionSelectedListener { position, item ->
                    picker.titleView.text = picker.wheelView.formatItem(position)
                }
            picker.show()
        }

        /**
         * 省市选择
         */
        public fun address(view: View) {
            val picker = AddressPicker(this@UserInfoActivity)
            picker.setAddressMode(AddressMode.PROVINCE_CITY_COUNTY)
            picker.setDefaultValue("湖南省", "长沙市", "岳麓区")
            picker.setOnAddressPickedListener(this@UserInfoActivity)
            picker.wheelLayout
                .setOnLinkageSelectedListener { first, second, third ->
                    picker.titleView.text = java.lang.String.format(
                        "%s%s%s",
                        picker.firstWheelView.formatItem(first),
                        picker.secondWheelView.formatItem(second),
                        picker.thirdWheelView.formatItem(third)
                    )
                }
            picker.show()
        }

        /**
         * 提交用户信息
         */
        public fun submit(view: View) {


            if (mDataBinding.etName.text.toString().isNotEmpty()) userInfoBean.emrHzName =
                mDataBinding.etName.text.toString() else {
                Toast.makeText(
                    getContext(), "请输入姓名", Toast.LENGTH_SHORT
                ).show()
                return
            }

            if (mDataBinding.etAge.text.toString().isNotEmpty()) userInfoBean.emrHzAge =
                mDataBinding.etAge.text.toString().toInt() else {
                Toast.makeText(
                    getContext(), "请输入年龄", Toast.LENGTH_SHORT
                ).show()
                return
            }

            if (mDataBinding.etSex.text.toString().isNotEmpty()) userInfoBean.emrHzSex =
                mDataBinding.etSex.text.toString() else {
                Toast.makeText(
                    getContext(), "请输入性别", Toast.LENGTH_SHORT
                ).show()
                return
            }

            if (mDataBinding.etJob.text.toString().isNotEmpty()) userInfoBean.emrHzJob =
                mDataBinding.etJob.text.toString() else {
                Toast.makeText(
                    getContext(), "请输入职业", Toast.LENGTH_SHORT
                ).show()
                return
            }

            if (mDataBinding.etBirth.text.toString().isNotEmpty()) userInfoBean.emrHzBirth =
                mDataBinding.etBirth.text.toString() else {
                Toast.makeText(
                    getContext(), "请输入出生日期", Toast.LENGTH_SHORT
                ).show()
                return
            }

            if (mDataBinding.etPlace.text.toString().isNotEmpty()) userInfoBean.emrHzPlace =
                mDataBinding.etPlace.text.toString() else {
                Toast.makeText(
                    getContext(), "请输入出生地", Toast.LENGTH_SHORT
                ).show()
                return
            }

            if (mDataBinding.etMarry.text.toString().isNotEmpty()) userInfoBean.emrHzMarry =
                mDataBinding.etMarry.text.toString() else {
                Toast.makeText(
                    getContext(), "请输入婚姻状态", Toast.LENGTH_SHORT
                ).show()
                return
            }
            mViewModel.updateUserInfo(userInfoBean)

        }
    }

    @SuppressLint("SetTextI18n")
    override fun onDatePicked(year: Int, month: Int, day: Int) {
        mDataBinding.etBirth.setText("$year-$month-$day")
        mDataBinding.etAge.setText("${2024 - year}")
        toast("$year-$month-$day")
    }

    override fun onOptionPicked(position: Int, item: Any?) {
        if (item is SexEntity) {
            mDataBinding.etSex.setText(item.name)
        }
    }

    @SuppressLint("SetTextI18n")
    override fun onAddressPicked(
        province: ProvinceEntity?,
        city: CityEntity?,
        county: CountyEntity?,
    ) {
        mDataBinding.etPlace.setText("${province?.name}-${city?.name}-${county?.name}")
        toast("${province?.name}-${city?.name}-${county?.name}")
    }
}